import os, cv2
import tqdm


words_list = [
    "A", "B", "C", "D", "E",
    "F", "G", "H", "J", "K", 
    "L", "M", "N", "P", "Q", 
    "R", "S", "T", "U", "V", 
    "W", "X", "Y", "Z", "0", 
    "1", "2", "3", "4", "5", 
    "6", "7", "8", "9" ]

con_list = [
    "皖", "沪", "津", "渝", "冀",
    "晋", "蒙", "辽", "吉", "黑",
    "苏", "浙", "京", "闽", "赣",
    "鲁", "豫", "鄂", "湘", "粤",
    "桂", "琼", "川", "贵", "云",
    "西", "陕", "甘", "青", "宁",
    "新"]


basefile =  '/home/train_data/hphm/CCPD'
imgsavepath = 'rec'

def det_():
 data = open(os.path.join(basefile,'base_data_det.txt'), 'w', encoding='UTF-8')
 for item in (os.listdir(os.path.join(basefile,'ccpd_base'))):
    path = os.path.join(basefile,'ccpd_base',item)
    _, _, bbox, points, label, _, _ = item.split('-')
    points = points.split('_')
    points = [_.split('&') for _ in points]
    tmp = points[-2:]+points[:2]
    points = []
    for point in tmp:
        points.append([int(_) for _ in point])
    label = label.split('_')
    con = con_list[int(label[0])]
    words = [words_list[int(_)] for _ in label[1:]]
    label = con+''.join(words)
    line = path+'\t'+'[{"transcription": "%s", "points": %s}]' % (label, str(points))
    line = line[:]+'\n'
    data.write(line)
 data.close()

def rec_():
     count = 0
     data = open(os.path.join(basefile,'base_data_rec.txt'), 'w', encoding='UTF-8')
     for item in os.listdir(os.path.join(basefile,"ccpd_base")):
        path = os.path.join(basefile,'ccpd_base/',item)
        _, _, bbox, _, label, _, _ = item.split('-')
        bbox = bbox.split('_')
        x1, y1 = bbox[0].split('&')
        x2, y2 = bbox[1].split('&')
        label = label.split('_')
        con = con_list[int(label[0])]
        words = [words_list[int(_)] for _ in label[1:]]
        label = con+''.join(words)
        bbox = [int(_) for _ in [x1, y1, x2, y2]]
        img = cv2.imread(path)
        crop = img[bbox[1]:bbox[3], bbox[0]:bbox[2], :]
        cv2.imwrite(os.path.join(basefile,imgsavepath,'%06d.jpg' % count), crop)
        data.write(os.path.join(imgsavepath,'%06d.jpg\t%s\n' % (count, label)))
        count += 1
     data.close()


   
rec_()




    
    